package site.marqstree.smartbutler.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;
import site.marqstree.smartbutler.R;
import site.marqstree.smartbutler.entity.User;
import site.marqstree.smartbutler.ui.CourierActivity;
import site.marqstree.smartbutler.ui.LoginActivity;
import site.marqstree.smartbutler.ui.PhoneActivity;
import site.marqstree.smartbutler.util.FileUtils;
import site.marqstree.smartbutler.util.L;
import site.marqstree.smartbutler.util.UtilTools;
import site.marqstree.smartbutler.view.CustomDialog;

/*
 * 项目名: SmartButler
 * 包名: site.marqstree.smartbutler.fragment
 * 文件名: UserFragment
 * 创建者: marqstree
 * 创建时间: 2019/12/27 14:23
 * 描述: TODO
 */
public class UserFragment extends Fragment implements View.OnClickListener {

    @BindView(R.id.profile_image)
    CircleImageView profileImage;
    @BindView(R.id.edit_user)
    TextView editUser;
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_sex)
    EditText etSex;
    @BindView(R.id.et_age)
    EditText etAge;
    @BindView(R.id.et_desc)
    EditText etDesc;
    @BindView(R.id.btn_update_ok)
    Button btnUpdateOk;
    @BindView(R.id.tv_courier)
    TextView tvCourier;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.btn_exit_user)
    Button btnExitUser;

    Button btnCamera;
    Button btnPicture;
    Button btnCancel;
    //ButterKnife解绑对象
    private Unbinder unBinder;

    //获取头像对话框(包括拍照、图库、取消3个按钮)
    private CustomDialog dialog;
    //拍照保存照片的文件名
    public static final String PHOTO_IMAGE_FILE_NAME = "avatar.jpg";
    //拍照请求码
    public static final int CAMERA_REQUEST_CODE = 100;
    //图库请求码
    public static final int IMAGE_REQUEST_CODE = 101;
    //裁剪图片请求码
    public static final int PHOTO_CROP_REQUEST_CODE = 102;
    //文件访问授权Uri前缀
    public static final String FILE_PROVIDER_AHTORITIES = "site.marqstree.smartbutler.fileprovider";
    //拍照保存图片文件
    private File tempFile = null;

    //1.将布局文件fragment_tab转换为View
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, null);
        unBinder = ButterKnife.bind(this, view);

        //初始化控件
        initView();

        return view;
    }

    //初始化控件
    private void initView() {

        //浏览状态
        setEnabled(false);

        //设置具体的值
        User userInfo = BmobUser.getCurrentUser(User.class);
        etUsername.setText(userInfo.getUsername());
        etAge.setText(userInfo.getAge() + "");
        etSex.setText(userInfo.isSex() ? getString(R.string.text_boy) : getString(R.string.text_girl_f));
        etDesc.setText(userInfo.getDesc());

        //从SharePreference中获取头像图像
        UtilTools.getImageFromShare(getActivity(), profileImage);

        //初始化获取头像dialog
        dialog = new CustomDialog(getActivity(), 0, 0,
                R.layout.dialog_photo, R.style.pop_anim_style, Gravity.BOTTOM, 0);
        //提示框以外点击无效
        dialog.setCancelable(false);
        //提示框以外点击无效
        dialog.setCancelable(false);
        btnCamera = (Button) dialog.findViewById(R.id.btn_camera);
        btnCamera.setOnClickListener(this);
        btnPicture = (Button) dialog.findViewById(R.id.btn_picture);
        btnPicture.setOnClickListener(this);
        btnCancel = (Button) dialog.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(this);
    }

    //控制焦点
    private void setEnabled(boolean is) {
        etUsername.setEnabled(is);
        etSex.setEnabled(is);
        etAge.setEnabled(is);
        etDesc.setEnabled(is);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //解除ButterKnife绑定
        unBinder.unbind();
    }

    //供外部调用，生成TabFragment实例，而不是new方式
    //此方法：采用Bundle模式，传入参数
    // 1）采用Bundle模式的好处：
    // 在用户中断操作，应用被系统放置在后台运行，系统自动保存Bundle，
    // 此Fragment可能会被系统销毁
    //当用户切换回此Fragment时，系统会自动调用onCreate方法，恢复自动保存的Bundle
    // 2）采用new方式创建Fragment不会自动恢复参数，导致Fragment中的数据丢失，界面空白。
    public static UserFragment newInstance() {
        UserFragment userFragment = new UserFragment();
        return userFragment;
    }

    //按钮点击事件
    @OnClick({R.id.btn_update_ok, R.id.btn_exit_user, R.id.edit_user,
            R.id.profile_image, R.id.tv_courier,R.id.tv_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //编辑资料
            case R.id.edit_user:
                setEnabled(true);
                btnUpdateOk.setVisibility(View.VISIBLE);
                break;
            //更新用户信息按钮
            case R.id.btn_update_ok:
                //1.拿到输入框的值
                String username = etUsername.getText().toString();
                String age = etAge.getText().toString();
                String sex = etSex.getText().toString();
                String desc = etDesc.getText().toString();

                //2.判断是否为空
                if (TextUtils.isEmpty(username) ||
                        TextUtils.isEmpty(age) ||
                        TextUtils.isEmpty(sex)) {
                    Toast.makeText(getActivity(), getString(R.string.text_tost_empty), Toast.LENGTH_SHORT).show();
                    return;
                }

                //3.更新属性
                User user = new User();
                user.setUsername(username);
                user.setAge(Integer.parseInt(age));
                //性别
                if (sex.equals(getString(R.string.text_boy))) {
                    user.setSex(true);
                } else {
                    user.setSex(false);
                }
                //简介
                if (!TextUtils.isEmpty(desc)) {
                    user.setDesc(desc);
                } else {
                    user.setDesc(getString(R.string.text_nothing));
                }
                BmobUser bmobUser = BmobUser.getCurrentUser(User.class);
                user.update(bmobUser.getObjectId(), new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            //修改成功
                            setEnabled(false);
                            btnUpdateOk.setVisibility(View.GONE);
                            Toast.makeText(getActivity(), R.string.text_editor_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), R.string.text_editor_failure, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                break;
            //退出登陆按钮
            case R.id.btn_exit_user:
                //清除缓存用户对象
                User.logOut();
                // 现在的currentUser是null了
                BmobUser currentUser = User.getCurrentUser(User.class);
                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
                break;
            //头像点击事件
            case R.id.profile_image:
                //显示获取头像对话框
                dialog.show();
                break;
            //物流查询点击事件
            case R.id.tv_courier:
                startActivity(new Intent(getActivity(), CourierActivity.class));
                break;
            case R.id.tv_phone:
                startActivity(new Intent(getActivity(), PhoneActivity.class));
                break;
        }
    }

    //获取头像对话框按钮
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //获取头像对话框的拍照按钮
            case R.id.btn_camera:
                //调用系统的拍照Activity
                toCamera();
                break;
            //获取头像对话框的相册按钮
            case R.id.btn_picture:
                //调用系统的相册Activity
                toPicture();
                break;
            //获取头像对话框的取消按钮
            case R.id.btn_cancel:
                //关闭获取头像对话框
                dialog.dismiss();
                break;
        }
    }

    //跳转到系统的拍照Activity
    //并将拍照得到的照片保存在sd卡中
    private void toCamera() {
        //拍照后照片存储的文件
        File file = new File(getActivity().getFilesDir(), PHOTO_IMAGE_FILE_NAME);
        Intent intent = new Intent();
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //将物理路径转换为Uri
            //FILE_PROVIDER_AHTORITIES:FileProvider对应的authority
            imageUri = FileProvider.getUriForFile(getActivity(), FILE_PROVIDER_AHTORITIES, file);
            //给系统拍照Activity授予读权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            imageUri = Uri.fromFile(file);
        }
        //定义拍照隐式意图
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //输出保存照片文件
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //调用系统拍照功能
        //CAMERA_REQUEST_CODE:调用系统相机请求码
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
        //关闭对话框
        dialog.dismiss();
    }

    //跳转到系统的相册Activity
    private void toPicture() {
        //定义选择图片隐式意图
        Intent intent = new Intent(Intent.ACTION_PICK);

        //类型为显示所有图片
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
        dialog.dismiss();
    }

    //调用系统裁剪照片Activity
    private void startPhotoZoom(File file) {
        if (file == null) {
            L.e("file == null");
            return;
        }
        //定义裁剪图片隐式意图
        Intent intent = new Intent("com.android.camera.action.CROP");

        //将物理路径转换为Uri
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //将物理路径转换为Uri
            //FILE_PROVIDER_AHTORITIES:FileProvider对应的authority
            imageUri = FileProvider.getUriForFile(getActivity(), FILE_PROVIDER_AHTORITIES, file);
            //给系统裁剪图片Activity授予读/写权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            imageUri = Uri.fromFile(file);
        }

        intent.setDataAndType(imageUri, "image/*");
        //设置裁剪
        intent.putExtra("crop", "true");
        //裁剪宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //裁剪图片的质量
        intent.putExtra("outputX", 160);
        intent.putExtra("outputY", 160);
        //发送裁剪后的照片数据
        intent.putExtra("return-data", true);

        //保存裁剪后的图片，覆盖掉原拍照图片
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, PHOTO_CROP_REQUEST_CODE);
    }

    //通过startActivityForResult启动子页面
    //子页面返回后，调用此函数
    //requestCode:请求码
    //resultCode：响应码
    //data：子页面返回的数据，子页面在关闭前通过setResult方法设置进来的，如果没有调用setResult，那么data=null
    //注意：
    //使用请求码区分是哪一个子页面返回数据
    //通过响应码，区分子页面传回的哪一类数据
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //接收相册返回图片
            case IMAGE_REQUEST_CODE:
                //获取图库选择器返回的图片Uri
                Uri inputUri = data.getData();
                //将选中图片复制到当前App目录下
                File copyFile = new File(getActivity().getFilesDir(), PHOTO_IMAGE_FILE_NAME);
                try {
                    FileUtils.copy(getActivity(), inputUri, copyFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //调用剪切功能生成头像图片
                startPhotoZoom(copyFile);
                break;
            //接收相机拍摄照片
            case CAMERA_REQUEST_CODE:
                //获取拍照生成的照片文件
                tempFile = new File(getActivity().getFilesDir(), PHOTO_IMAGE_FILE_NAME);
                //调用裁剪Activity
                startPhotoZoom(tempFile);
                break;
            //接收裁剪返回头像图片
            case PHOTO_CROP_REQUEST_CODE:
                //获取裁剪后下图的Uri
                File file = new File(getActivity().getFilesDir(), PHOTO_IMAGE_FILE_NAME);
                //将Uri转换为Bitmap
                Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
                //将裁剪的bitmap显示在imageview控件上
                profileImage.setImageBitmap(bitmap);
                //将图片保存到SharePreference
                UtilTools.putImageToShare(getActivity(), profileImage);
                break;
        }
    }

}